package com.yanyeori.framework.jira.jiraclient;

import net.sf.json.JSON;
import net.sf.json.JSONObject;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.springframework.util.StreamUtils;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Date;

/**
 * Represents an issue attachment.
 */
public class Attachment extends Resource {

    private User author = null;
    private String filename = null;
    private Date created = null;
    private int size = 0;
    private String mimeType = null;
    private String content = null;

    /**
     * Creates an attachment from a JSON payload.
     *
     * @param restclient REST client instance
     * @param json       JSON payload
     */
    protected Attachment(RestClient restclient, JSONObject json) {
        super(restclient);

        if (json != null)
            deserialise(json);
    }

    private void deserialise(JSONObject json) {
        self = Field.getString(json.get("self"));
        id = Field.getString(json.get("id"));
        author = Field.getResource(User.class, json.get("author"), restclient);
        filename = Field.getString(json.get("filename"));
        created = Field.getDateTime(json.get("created"));
        size = Field.getInteger(json.get("size"));
        mimeType = Field.getString(json.get("mimeType"));
        content = Field.getString(json.get("content"));
    }

    /**
     * Retrieves the given attachment record.
     *
     * @param restclient REST client instance
     * @param id         Internal JIRA ID of the attachment
     * @return an attachment instance
     * @throws JiraException when the retrieval fails
     */
    public static Attachment get(RestClient restclient, String id) throws JiraException {
        JSON result;

        try {
            result = restclient.get(getBaseUri() + "attachment/" + id);
        } catch (Exception ex) {
            throw new JiraException("Failed to retrieve attachment " + id, ex);
        }

        if (!(result instanceof JSONObject))
            throw new JiraException("JSON payload is malformed");

        return new Attachment(restclient, (JSONObject) result);
    }

    /**
     * Downloads attachment to byte array
     *
     * @return a byte[]
     * @throws JiraException when the download fails
     */
    public byte[] download() throws JiraException {
        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        try (InputStream input = downloadToStream()) {
            if (input != null) {
                byte[] buffer = new byte[StreamUtils.BUFFER_SIZE];
                int len;
                while ((len = input.read(buffer)) > -1) {
                    bos.write(buffer, 0, len);
                }
                bos.flush();
            }
        } catch (IOException e) {
            throw new JiraException(String.format("Failed downloading attachment from %s: %s", this.content, e.getMessage()));
        }
        return bos.toByteArray();
    }

    /**
     * Downloads attachment to InputStream
     *
     * @return a InputStream
     * @throws JiraException when the download fails
     */
    public InputStream downloadToStream() throws JiraException {
        try {
            HttpGet get = new HttpGet(content);
            RequestConfig config = RequestConfig.custom().build();
            get.setConfig(config);
            HttpResponse response = restclient.requestHttpResponse(get);
            HttpEntity entity = response.getEntity();
            return entity.getContent();
        } catch (IOException e) {
            throw new JiraException(String.format("Failed downloading attachment from %s: %s", this.content, e.getMessage()));
        }
    }

    @Override
    public String toString() {
        return getContentUrl();
    }

    public User getAuthor() {
        return author;
    }

    public Date getCreatedDate() {
        return created;
    }

    public String getContentUrl() {
        return content;
    }

    public String getFileName() {
        return filename;
    }

    public String getMimeType() {
        return mimeType;
    }

    public int getSize() {
        return size;
    }
}

